<template>
  <el-dialog
    v-model="dialogVisible"
    title="导入号码"
    :width="dailogWidth"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      style="max-width: 600px"
      :model="dataForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      v-loading="loading"
    >
      <el-form-item label="号码分组" prop="groupId" label-position="right">
        <div style="display: flex; justify-content: space-between;width: 90%;">
          <el-select v-model="dataForm.groupId" placeholder="请选择" style="margin-right: 10px;" :clearable="true" filterable>
            <el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-button @click="handleAddGroup">新建分组</el-button>
        </div>
      </el-form-item>
      <el-form-item label="国家" prop="country" label-position="right" v-if="false">
        <el-select v-model="dataForm.country" placeholder="请选择" style="width: 90%;" :clearable="true" filterable>
          <el-option v-for="item in countriesList" :key="item.code" :label="item.name" :value="item.code">
            <span class="flag-icon" :class="`flag-icon-${item.code.toLowerCase()}`"></span>
            <span style="margin-left: 5px;">{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件上传" prop="file" label-position="right">
        <el-upload
          v-model:file-list="fileList"
          ref="upload"
          class="upload-demo"
          action=""
          :limit="1"
          :on-change="handleUploadChange"
          :on-exceed="handleExceed"
          :auto-upload="false"
        >
          <template #trigger>
            <el-button type="primary">选择文件</el-button>
          </template>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer" v-loading="loading">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { fileInfoUpload } from '@/utils/formRequest'
import useCountries from "@/hooks/useCountries";
const { countriesList, getCountryName } = useCountries()
import { groupListApi, importNumberApi } from '@/api/equipmentManagement/massTexting.api'
import { formatParams } from "@/utils";
import useToggle from "@/hooks/useToggle";
import useDailogWidth from "@/hooks/useDailogWidth";
const dailogWidth = useDailogWidth("90%", "35%")
const [loading, , setLoading] = useToggle();
const [dialogVisible, , setDialogVisible] = useToggle();
const emit = defineEmits(["refresh", "handleOpenAddGroupForm"]);
const dataForm = ref({
  groupId: "",
  // country: "",
  file: null,
})
const fileList = ref([])
const rules = {
  groupId: [{ required: true, message: '请选择分组', trigger: 'change' },],
  file: [{ required: true, message: '请上传文件', trigger: 'change' },],
}

const file = ref(null)
const handleUploadChange = async (files, list) => {
  fileList.value = list
  dataForm.value.file = files.raw
  await formRef.value.validate(() => {})
}

const handleClose = () => {
  setDialogVisible(false)
}
const handleOpen = (params) => {
  setDialogVisible(true)

  nextTick(() => {
    getGroupList()
    resetForm()
    if(params) {
      dataForm.value.id = params.id || void undefined
      dataForm.value.name = params.name
      dataForm.value.remark = params.remark
      dataForm.value.app = params.app
      dataForm.value.bundle = params.bundle
    }
  })
}

const groupList = ref([])
const getGroupList = async () => {
  const res = await groupListApi(formatParams({
    page: 1,
    size: 1000,
    app: 'WA',
  }))
  groupList.value = res.rows
}

const formRef = ref(null)
const submitForm = async () => {

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      setLoading(true)

      const params = `?app=WA&groupId=${dataForm.value.groupId}`
      const fileData = new FormData()
      fileData.append('file', dataForm.value.file)

      fileInfoUpload(`/mass/number/import${params}`, fileData).then(res => {
        emit("refresh");
        setLoading(false)
        handleClose()
      }).finally(() => {
        setLoading(false)
        handleClose()
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = () => {
  if (!formRef.value) return
  fileList.value = []
  formRef.value.resetFields()
}

const handleAddGroup = () => {
  emit("handleOpenAddGroupForm", getGroupList)
}

defineExpose({
  handleOpen,
})
</script>
